package com.weichat.converter;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.weichat.dto.OrderDTO;
import com.weichat.entity.OrderDetail;
import com.weichat.exception.SellException;
import com.weichat.form.OrderForm;
import com.weichat.util.ResultEnum;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA
 * Created By HZP
 * Date: 2018/6/19
 * Time: 22:50
 */
@Slf4j
public class OrderFormToOrderDTOConverter {

    public static OrderDTO converter(OrderForm orderForm){
        OrderDTO orderDTO =new OrderDTO();
        orderDTO.setBuyerPhone(orderForm.getPhone());
        orderDTO.setBuyerName(orderForm.getName());
        orderDTO.setBuyerOpenid(orderForm.getOpenid());
        orderDTO.setBuyerAddress(orderForm.getAddress());

        Gson gson=new Gson();
        List<OrderDetail> orderDetailsList=new ArrayList<>();
        try {
             orderDetailsList=gson.fromJson(
                     orderForm.getItems(), new TypeToken<List<OrderDetail>>(){}.getType()
             );

        }catch (Exception e){
            log.error("对象转化 错误");
            throw new SellException(ResultEnum.PARAM_ERROR);
        }

        orderDTO.setOrderDetails(orderDetailsList);

        return orderDTO;
    }

}
